<template>
  <a-upload
    v-model:file-list="fileList"
    name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    action=""
    :before-upload="beforeUpload"
    :custom-request="uploadImage"
  >
    <img
      class="w-full h-full"
      style="object-fit: cover"
      v-if="imageUrl"
      :src="imageUrl"
      alt="avatar"
    />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined text-6 v-else></plus-outlined>
    </div>
  </a-upload>
</template>
<script lang="ts" setup>
import { uploadFile } from '@/api/global';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = defineModel<string>({ default: '' });

const uploadImage = (data: any) => {
  loading.value = true;
  uploadFile(data.file, 'OptionLogo').then(res => {
    loading.value = false;
    if (res.code === 'ok') {
      imageUrl.value = res.data;
    }
  });
};

const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('您只能上传jpg、jpeg和png格式的图片');
  }
  const isLt256k = file.size / 1024 < 256;
  if (!isLt256k) {
    message.error('图片大小不能超过256KB');
  }
  return isJpgOrPng && isLt256k;
};
</script>
<style lang="scss" scoped>
.avatar-uploader > .ant-upload {
  width: 80px;
  height: 80px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
